package com.jinke.api.modules.app.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.jinke.api.common.api.CommonResult;
import com.jinke.api.modules.app.model.UserApi;
import com.jinke.api.modules.app.service.UserApiService;
import com.jinke.api.security.util.AdminUserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author macro
 * @since 2024-01-16
 */
@RestController
@RequestMapping("/app/user/api")
@Api(value = "API设定", tags = "API设定")
public class UserApiController {

    @Resource
    UserApiService userApiService;

    @ApiOperation(value = "查询API数据", notes = "进入页面先调用这个接口获取API信息，才能继续调用保存和重置")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<UserApi> info() {
        LambdaQueryWrapper<UserApi> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserApi::getUserId, AdminUserUtil.getUserId());
        queryWrapper.last("LIMIT 1");
        UserApi userApi = userApiService.getOne(queryWrapper);

        if (userApi == null) {
            userApi = new UserApi();
            userApi.setUserId(AdminUserUtil.getUserId());
            userApi.setStatus(0);
            String key = UUID.randomUUID().toString().replace("-", "");
            userApi.setApiKey(key);
            userApiService.save(userApi);
        }

        return CommonResult.success(userApi);
    }

    @ApiOperation(value = "保存", notes = "这个接口只需要传status，0关闭，1启用")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<?> save(@RequestBody UserApi request) {
        LambdaUpdateWrapper<UserApi> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(UserApi::getUserId, AdminUserUtil.getUserId());
        updateWrapper.set(UserApi::getStatus, request.getStatus());
        return CommonResult.success(userApiService.update(null, updateWrapper));
    }

    @ApiOperation(value = "重置apiKey")
    @RequestMapping(value = "/reset", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<String> reset() {
        LambdaUpdateWrapper<UserApi> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(UserApi::getUserId, AdminUserUtil.getUserId());
        String key = UUID.randomUUID().toString().replace("-", "");
        updateWrapper.set(UserApi::getApiKey, key);
        if (userApiService.update(null, updateWrapper)) {
            return CommonResult.success(key);
        } else {
            return CommonResult.failed();
        }
    }

}

